import { Input, Mask, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { BankData, GetChooseMethod, GetUserInfo } from '../../../api/mine'
import { getBankList, unionApplyWithdraw as ApplyWithdraw } from '../../../api/union'
import NavBar from '../../../components/Navbar'
import AmePopup from '../../../components/Popup'
// import appSdk from '../../../utils/app_sdk';
import './index.less'
import AmeModal from '../../../components/AmeModal'

import aliImg from '../../../images/ali.png'
import bankImg from '../../../images/bank.png'

function Income() {
  const navigate = useNavigate()
  const [visible, setVisible] = useState(false)
  const [bankData, setBankData] = useState([])
  const [activeBank, setActiveBank] = useState([])
  const [userInfo, setUserInfo] = useState({
    service_fee: 6,
    mibi: 0,
    union_mibi: 0,
    mizuan: 0,
    is_idcard: 0,
    is_fase_order: 0,
    is_pig_sign: 0
  })

  const [withdrawVisible, setWithdrawVisible] = useState(false) // 提现确认

  const [withdrawValue, setWithdrawValue] = useState(1)

  const onSelectBank = () => {
    setVisible(!visible)
    // navigate('/bank_management')
  }

  // 签约提现
  const getPigSignInfo = () => {
    BankData().then((res) => {
      console.log('getPigSignInfo', res)
      if (res.data.jump_url) {
        window.location.href = res.data.jump_url
      }
    })
  }

  const [chooseMethod, setChooseMethod] = useState()
  const getInfo = () => {
    Toast.show({
      content: '加载中',
      maskClickable: false,
      icon: 'loading'
    })
    GetUserInfo().then((res) => {
      setUserInfo(res.data)
    })
    GetChooseMethod().then((res) => {
      console.log('当前选中的', res)
      // bank_no ali_account type bank_name
      setChooseMethod(res.data)
    })
    getBankList({
      type: 1
    }).then((res) => {
      Toast.clear()
      const list = res.data
      const item = list.find((item) => item.is_use)
      if (item) {
        setBankData([{ ...item, name: `${item.bank_name}(${item.bank_no?.slice(item.bank_no.length - 4)})` }])
        setActiveBank({ ...item, name: `${item.bank_name}(${item.bank_no?.slice(item.bank_no.length - 4)})` })
      }
    })
  }

  useEffect(() => {
    getInfo()
  }, [])

  const applyData = () => {
    if (+withdrawValue) {
      if (chooseMethod && chooseMethod.type) {
        if (userInfo.is_pig_sign === 1) {
          Toast.show({
            icon: 'loading',
            content: '提现提交中...',
            maskClickable: false
          })
          ApplyWithdraw({ money: withdrawValue })
            .then((res) => {
              if (res.code === 1) {
                getInfo()
                setWithdrawVisible(false)
                navigate('/result')
              } else {
                Toast.show({
                  icon: 'fail',
                  content: res.message,
                  maskClickable: false
                })
              }
            })
            .catch((reason) => {
              Toast.show({
                icon: 'fail',
                content: reason.message || '服务器异常',
                maskClickable: false
              })
            })
        } else {
          console.log('未签约准备请求签约')
          getPigSignInfo()
        }
      } else {
        Toast.show({
          content: '请先选择提现方式'
        })
      }
    } else {
      Toast.show({
        content: '当前无可提金额'
      })
    }
  }

  const handleWithdraw = () => {
    if (withdrawValue && withdrawValue >= 1) {
      setWithdrawVisible(true)
    } else {
      Toast.show({
        content: '请输入有效金额'
      })
    }
  }

  // 计算可提现金额
  const countMoney = () => {
    const { service_fee, union_mibi } = userInfo
    if (!Number(withdrawValue) || Number(union_mibi) < 0) return '0.00'
    if (!Number(service_fee)) return withdrawValue || '0.00'
    return (withdrawValue - (service_fee / 100) * withdrawValue).toFixed(2)
    // return ((withdrawValue) * (1 - (service_fee / 100))).toFixed(2) || 0
  }

  return (
    <div className="mine_income">
      <NavBar other={<span onClick={() => navigate('/union_detail')}>明细</span>} title={'收益提现'} />
      <div>
        <div className="mine_card card">
          <div className="tit">{chooseMethod ? (chooseMethod?.type === 1 ? '到账银行卡' : '到账支付宝') : '选择提现方式'}</div>
          <div className="line"></div>
          <div className="content" onClick={onSelectBank}>
            <div className="card_info">{chooseMethod?.type === 1 ? chooseMethod?.bank_name : chooseMethod?.ali_account || ''}</div>
            <span className="tips">48小时之内到账</span>
          </div>
          <div className="arrow_icon"></div>
        </div>
        <div className="mine_card income">
          <div className="tit">提现金额</div>
          {/* <div className="line"></div> */}
          <div className="content" style={{ padding: 0 }}>
            {/* <div className="wallet">{userInfo?.union_mibi || 0}</div> */}
            <div className="wallet">
              <Input
                onChange={(e) => {
                  setWithdrawValue(e.replace(/[^\d]/g, ''))
                }}
                // type="number"
                // onChange={setWithdrawValue}
                onBlur={(e) => {
                  console.log(e, Math.floor(userInfo?.union_mibi))
                  if (+e.target.value > Math.floor(userInfo?.union_mibi)) {
                    setWithdrawValue(Math.floor(userInfo?.union_mibi))
                  }
                }}
                // min={1}
                // max={Math.floor(userInfo?.union_mibi)}
                value={withdrawValue ? withdrawValue : ''}
              />
            </div>
          </div>
        </div>
        <div className="less_money">
          可提现金额：{userInfo?.union_mibi || 0} &nbsp;
          {userInfo?.union_mibi ? (
            <span
              onClick={() => {
                setWithdrawValue(Math.floor(userInfo?.union_mibi || 0))
              }}
            >
              全部提现
            </span>
          ) : (
            ''
          )}
        </div>
      </div>
      <div className="fixed_content">
        <div className={'btn'} onClick={handleWithdraw}>
          立刻提现
        </div>
      </div>
      <Mask visible={visible} style={{ zIndex: 10 }} />
      <AmePopup visible={visible} AmePopupClose={setVisible}>
        <div className="bank_pop_content">
          <div className="bank_title">选择提现方式</div>
          <div className="banks">
            <div
              className="bank_item"
              onClick={() => {
                navigate('/person_list?type=2')
              }}
            >
              <div className="icon">
                <img src={aliImg} alt="" width={36} height={36} />
              </div>
              <div className="bank_info">
                <div className="bank_name">提现到支付宝账户</div>
                <span className="tips">48小时之内到账</span>
              </div>
            </div>
            <div
              className="bank_item"
              onClick={() => {
                navigate('/bank_management?type=1')
              }}
            >
              <div className="icon">
                <img src={bankImg} alt="" width={36} height={36} />
              </div>
              <div className="bank_info">
                <div className="bank_name">提现到银行卡</div>
                <span className="tips">48小时之内到账</span>
              </div>
            </div>
          </div>
        </div>
      </AmePopup>

      <AmeModal
        visible={withdrawVisible}
        className="modal2"
        title={<div>确定提现信息</div>}
        confirmText="确认"
        onCancel={() => setWithdrawVisible(false)}
        onConfirm={applyData}
      >
        {/* <div className='sub_tit'>点击输入提现金额</div> */}
        <div className="money" style={{ marginTop: 10 }}>
          <span>￥</span>
          {countMoney()}
        </div>
        <div className="fee_tips">
          {/* <p>
            <span>服务费</span>
            <span>{((+withdrawValue) * (userInfo?.service_fee / 100)).toFixed(2)}</span>
          </p> */}
          <p>
            <span>服务及个人税费</span>
            <span>{+userInfo?.service_fee || 0}%</span>
          </p>
        </div>
      </AmeModal>
    </div>
  )
}

export default Income
